package org.stvd.core.util.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 使用HttpClient组件请求url
 */
public class HttpClientUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    // 编码格式。发送编码格式统一用UTF-8
    private static final String ENCODING = "UTF-8";
    // 设置连接超时时间，单位毫秒。
    private static final int CONNECT_TIMEOUT = 10000;
    // 请求获取数据的超时时间(即响应时间)，单位毫秒。
    private static final int SOCKET_TIMEOUT = 30000;

    public static CloseableHttpClient createIgnoreVerifySSL() {
        SSLContext sslcontext = null;
        try {
            sslcontext = SSLContext.getInstance("SSLv3");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                String paramString) { } 

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                String paramString) { } 

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        try {
            if (sslcontext != null) {
                sslcontext.init(null, new TrustManager[] {trustManager}, null);
                // 设置协议http和https对应的处理socket链接工厂的对象
                Registry<ConnectionSocketFactory> socketFactoryRegistry =
                    RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE)
                        .register("https", new SSLConnectionSocketFactory(sslcontext)).build();
                PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
                return HttpClients.custom().setConnectionManager(connManager).build();
            }
        } catch (KeyManagementException e) {
            e.printStackTrace(); 
        }
        return null;
    }

    /**
     * 发送get请求；带请求头和请求参数  
     * 
     * @param url
     *            请求地址
     * @param headers
     *            请求头集合
     * @param params
     *            请求参数集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) {
        long time = System.currentTimeMillis();
        // 创建httpClient对象
        CloseableHttpClient httpClient = createIgnoreVerifySSL();
        if (httpClient == null) {
            httpClient = HttpClients.createDefault();
        }
        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;
        // 请求结果
        HttpClientResult result = null;
        // 请求url
        String getUrl = url;
        try {
            // 创建访问的地址
            URIBuilder uriBuilder = new URIBuilder(url);
            if (params != null) {
                Set<Entry<String, String>> entrySet = params.entrySet();
                for (Entry<String, String> entry : entrySet) {
                    uriBuilder.setParameter(entry.getKey(), entry.getValue());
                }
            }
            getUrl = uriBuilder.build().toString();
            // 创建http对象
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            RequestConfig requestConfig =
                RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
            httpGet.setConfig(requestConfig);

            // 设置请求头
            packageHeader(headers, httpGet);

            // 执行请求并获得响应结果
            result = getHttpClientResult(httpResponse, httpClient, httpGet);
        } catch (Exception e) {
            e.printStackTrace();
            result = new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            result.setMessage(e.getMessage());
        } finally {
            // 释放资源
            release(httpResponse, httpClient);
            // 输出日志
            StringBuilder strBuilder = new StringBuilder().append("GET ").append(getUrl).append(' ');
            if (result != null) {
                strBuilder.append(result.getCode());
            }
            strBuilder.append(' ').append((System.currentTimeMillis() - time) / 1000d).append('s');
            logger.info(strBuilder.toString());
        }

        return result;
    }

    public static HttpClientResult doGet(String url, Map<String, String> params) {
        return doGet(url, null, params);
    }

    public static HttpClientResult doGet(String url) {
        return doGet(url, null, null);
    }

    /**
     * 发送post请求；带请求头和请求参数
     * 
     * @param url
     *            请求地址
     * @param headers
     *            请求头集合
     * @param params
     *            请求参数集合
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws Exception
     */
    public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) {
        long time = System.currentTimeMillis();
        // 创建httpClient对象
        CloseableHttpClient httpClient = createIgnoreVerifySSL();
        if (httpClient == null) {
            httpClient = HttpClients.createDefault();
        }
        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;
        // 请求结果
        HttpClientResult result = null;
        try {
            // 创建http对象
            HttpPost httpPost = new HttpPost(url);
            /**
             * setConnectTimeout：设置连接超时时间，单位毫秒。 setConnectionRequestTimeout：设置从connect Manager(连接池)获取Connection
             * 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。 setSocketTimeout：请求获取数据的超时时间(即响应时间)，单位毫秒。
             * 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
             */
            RequestConfig requestConfig =
                RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
            httpPost.setConfig(requestConfig);
            // 设置请求头
            /*
             * httpPost.setHeader("Cookie", ""); httpPost.setHeader("Connection",
             * "keep-alive"); httpPost.setHeader("Accept", "application/json");
             * httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
             * httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
             * httpPost.setHeader("User-Agent",
             * "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
             * );
             */
            packageHeader(headers, httpPost);

            // 封装请求参数
            packageParam(params, httpPost);

            // 执行请求并获得响应结果
            result = getHttpClientResult(httpResponse, httpClient, httpPost);
        } catch (Exception e) {
            e.printStackTrace();
            result = new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            result.setMessage(e.getMessage());
        } finally {
            // 释放资源
            release(httpResponse, httpClient);
            // 输出日志
            StringBuilder strBuilder = new StringBuilder().append("POST ").append(url).append(' ');
            if (result != null) {
                strBuilder.append(result.getCode());
            }
            strBuilder.append(' ').append((System.currentTimeMillis() - time) / 1000d).append('s');
            logger.info(strBuilder.toString());
        }
        return result;
    }

    public static HttpClientResult doPost(String url, Map<String, String> params) {
        return doPost(url, null, params);
    }

    /**
     * post请求，使用requestBody提交json数据
     * 
     * @param url
     * @param dataStr
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static HttpClientResult doPostJson(String url, String dataStr) {
        long time = System.currentTimeMillis();
        // 创建httpClient对象
        CloseableHttpClient httpClient = createIgnoreVerifySSL();
        if (httpClient == null) {
            httpClient = HttpClients.createDefault();
        }
        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;
        // 请求结果
        HttpClientResult result = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(CONNECT_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
            httpPost.setHeader(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
            // 设置期望服务端返回的编码
            HttpEntity entityRequest = new StringEntity(dataStr, ENCODING);
            httpPost.setEntity(entityRequest);
            httpPost.setConfig(requestConfig);
            // 执行请求
            result = getHttpClientResult(httpResponse, httpClient, httpPost);
        } catch (Exception e) {
            e.printStackTrace();
            result = new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            result.setMessage(e.getMessage());
        } finally {
            release(httpResponse, httpClient);
            // 输出日志
            StringBuilder strBuilder = new StringBuilder().append("POST JSON ").append(url).append(' ');
            if (result != null) {
                strBuilder.append(result.getCode());
            }
            strBuilder.append(' ').append((System.currentTimeMillis() - time) / 1000d).append('s');
            logger.info(strBuilder.toString());
        }
        return result;
    }

    /**
     * http请求信息转成字符串
     * 
     * @param entity
     * @return
     */
    public static String responseAsString(HttpEntity entity) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            entity.writeTo(baos);
            return new String(baos.toByteArray(), ENCODING);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * Description: 封装请求头
     * 
     * @param params
     * @param httpMethod
     */
    public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
        // 封装请求头
        if (params != null) {
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
                // 设置到请求头到HttpRequestBase对象中
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Description: 封装请求参数
     * 
     * @param params
     * @param httpMethod
     */
    public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
        throws UnsupportedEncodingException {
        // 封装请求参数
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            // 设置到请求的http对象中
            httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
        }
    }

    /**
     * Description: 获得响应结果  
     * 
     * @param httpResponse
     * @param httpClient
     * @param httpMethod
     * @return
     * @throws Exception
     */
    public static HttpClientResult getHttpClientResult(CloseableHttpResponse closeableHttpResponse,
        CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
        CloseableHttpResponse httpResponse = closeableHttpResponse;
        // 执行请求
        httpResponse = httpClient.execute(httpMethod);
        // 获取返回结果
        if (httpResponse != null && httpResponse.getStatusLine() != null) {
            HeaderIterator redirect = httpResponse.headerIterator("location");
            if (redirect.hasNext()) {
                System.out.println("location:" + redirect.next().toString());
            }

            String content = "";
            if (httpResponse.getEntity() != null) {
                content = responseAsString(httpResponse.getEntity());
            }
            return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
        }
        return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }

    /**
     * Description: 释放资源  
     * 
     * @param httpResponse
     * @param httpClient
     * @throws IOException
     */
    public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) {
        // 释放资源
        if (httpResponse != null) {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}